package com.example.javaapiclient.strategy.aggregation;

import co.elastic.clients.elasticsearch._types.aggregations.Aggregation;
import com.example.javaapiclient.entity.common.AggregationParamEntity;
import com.example.javaapiclient.exception.BizException;
import com.example.javaapiclient.utils.EmptyUtil;
import com.example.javaapiclient.utils.SpringContextUtil;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service(value = "termsParseAggregation")
public class TermsParseAggregationServiceImpl implements ParseAggregationService {
    @Override
    public Aggregation parseAggregation(AggregationParamEntity param) throws BizException {

        if (EmptyUtil.isEmpty(param.getSubAgg())){
            return Aggregation.of(aggregation->aggregation.terms(
                    termsAggregation->termsAggregation
                            .field(param.getField())
                            .size(EmptyUtil.isEmpty(param.getSize())?10:param.getSize())
            ));
        }

        Map<String, Aggregation> subAggMap = new HashMap<>();
        for (AggregationParamEntity e:param.getSubAgg()) {
            ParseAggregationService service = (ParseAggregationService) SpringContextUtil.getBean(e.getType().toString()+"ParseAggregation");
            subAggMap.put(e.getName(),service.parseAggregation(e));
        }
        return Aggregation.of(aggregation->aggregation.terms(
                termsAggregation->termsAggregation
                        .field(param.getField())
                        .size(EmptyUtil.isEmpty(param.getSize())?10:param.getSize())
        ).aggregations(subAggMap));
    }
}
